简体   繁体   中英

C# - syntax to make these true key-value pairs

ASP.Net MVC Web app - I have the following code in my Web.config file:

<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://www.contoso.com -->
    <section name="entityFramework" type="words, EntityFramework, Version=numbers, Culture=more words" />
  </configSections>
  <appSettings>
    <add key="x-coord" value="x1,x2,x3" />
    <add key="y-coord" value="y1,y2,y3" />
  </appSettings>
</configuration>  

And this is a conditional inside the method that uses the <appSettings> key-values:

if

(ModelState.IsValid && 
((ConfigurationManager.AppSettings["x-coord"].Contains(postModel.xCoordinate.ToLower()) 
& ConfigurationManager.AppSettings["y-coord"].Contains(postModel.yCoordinate.ToLower))))

    {
        return View(postModel);
    }

The issue is that as this code is written, as long as any of the x-coord values are passed, and any of the y-coord values are passed, the conditional will evaluate to true.

I need to have the code function such that x1 and y1 must be passed to evaluate to true, OR, x2 and y2, OR, x3 and y3, such that these are true key-value pairs, as opposed to just two Lists.

I believe this all comes down to the Contains method, which is what is allowing any pair of x and y to be allowed. I just don't know how to go about enforcing strict pairing as outlined above.

You seem to be confused about what your code is doing here. When you set <add key="x-coord" value="x1,x2,x3" /> in your web.config you're adding a key with a single value which is a string of "x1,x2,x3" so when you call ConfigurationManager.AppSettings["x-coord"].Contains(postModel.xCoordinate.ToLower()) all you're doing is checking if the x-coord string contains whatever is in postModel.xCoordinate (converted to lowercase obviously). You then do an entirely separate check on your 'y-coord` value. There is no relationship between the two.

I'm not a fan of using your web.config for holding application logic like this, but if this is really the way you want to go, I'd set it up so you can split the string and process coords separately. So something like:

<add key="coords" value="x1:y1,x2:y2,x3:y3" />

And then you can do something like:

        var coords = ConfigurationManager.AppSettings["x-coord"].Split(',').ToList();
        coords.ForEach(c =>
        {
            var coord = c.Split(':');
            if (coord[0].Equals(postModel.xCoordinate.ToLower()) && coord[1].Equals(postModel.yCoordinate.ToLower()))
            {
                return View(postModel);
            }
        }
        );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM