@@ -251,21 +251,21 @@ private void HandleSensorRequest(HttpListenerRequest request, Dictionary<string,
251251 {
252252 IDictionary < string , string > dict = ToDictionary ( HttpUtility . ParseQueryString ( request . Url . Query ) ) ;
253253
254- if ( dict . ContainsKey ( "action" ) )
254+ if ( dict . TryGetValue ( "action" , out string action ) )
255255 {
256- if ( dict . ContainsKey ( "id" ) )
256+ if ( dict . TryGetValue ( "id" , out string identifier ) )
257257 {
258- SensorNode sNode = FindSensor ( _root , dict [ "id" ] )
259- ?? throw new ArgumentException ( "Unknown id " + dict [ "id" ] + " specified" ) ;
260- if ( dict [ " action" ] == "ResetMinMax" )
258+ SensorNode sNode = FindSensor ( _root , identifier )
259+ ?? throw new ArgumentException ( "Unknown id " + identifier + " specified" ) ;
260+ if ( action == "ResetMinMax" )
261261 {
262262 // Reset Min/Max, then return Sensor values...
263263 sNode . Sensor . ResetMin ( ) ;
264264 sNode . Sensor . ResetMax ( ) ;
265- dict [ " action" ] = "Get" ;
265+ action = "Get" ;
266266 }
267267
268- switch ( dict [ " action" ] )
268+ switch ( action )
269269 {
270270 case "Set" when dict . ContainsKey ( "value" ) :
271271 SetSensorControlValue ( sNode , dict [ "value" ] ) ;
@@ -279,7 +279,7 @@ private void HandleSensorRequest(HttpListenerRequest request, Dictionary<string,
279279 result [ "format" ] = sNode . Format ;
280280 break ;
281281 default :
282- throw new ArgumentException ( "Unknown action type " + dict [ " action" ] ) ;
282+ throw new ArgumentException ( "Unknown action type " + action ) ;
283283 }
284284 }
285285 else
@@ -341,6 +341,8 @@ private async Task HandleContextAsync(HttpListenerContext context)
341341 }
342342 }
343343
344+ try
345+ {
344346 if ( authenticated )
345347 {
346348 switch ( request . HttpMethod )
@@ -422,15 +424,23 @@ private async Task HandleContextAsync(HttpListenerContext context)
422424 await SendResponseAsync ( context . Response , responseString , "text/html" ) ;
423425 }
424426
425- try
427+ context . Response . Close ( ) ;
428+ }
429+ catch ( ArgumentException ex )
426430 {
431+ context . Response . StatusCode = 400 ;
432+ string responseString = @$ "<HTML><HEAD><TITLE>400 Bad Request</TITLE></HEAD>
433+ <BODY><H4>400 Bad Request</H4>
434+ { ex . Message } </BODY></HTML> " ;
435+ await SendResponseAsync ( context . Response , responseString , "text/html" ) ;
427436 context . Response . Close ( ) ;
428437 }
429438 catch
430439 {
431440 // client closed connection before the content was sent
432441 }
433442 }
443+
434444 private async Task ServeResourceFileAsync ( HttpListenerResponse response , string name , string ext )
435445 {
436446 // resource names do not support the hyphen
0 commit comments