Showing posts with label asp.net-web-api. Show all posts
Showing posts with label asp.net-web-api. Show all posts

Thursday, September 20, 2018

Clients are unable to connect to server during selenium tests

Leave a Comment

I'm working on selenium tests (written in C# using the chrome webdriver) for a javascript web app that uses a backend server running on WebApi 5.2.4. It is CORS enabled with very permissive settingss:

namespace SealingService {     public static class WebApiConfig     {         public static void Register(HttpConfiguration config)         {             // Web API configuration and services              var cors = new EnableCorsAttribute("*", "*", "*");             config.EnableCors(cors);              // etc...         }     } } 

Normally everything works as expected. But on some machines when the server is started by the test scripts the client encounters CORS errors on every request. The chrome dev console shows the standard Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. message. The server logs show that the OPTION requests are reaching it, and it's sending a response.

When I try to access any of the API routes manually, the server returns the generic ASP.NET 404 page. This makes me think that our CORS configuration actually could be working correctly, but the server is not being started/configured correctly by our test script, so the routes are not being registered. Thus, all API routes are returning the 404 page, which is obviously not CORS enabled.

This is the applicationhost.config used by IIS during the tests. This is how the server is started by the test script:

public static Process StartIIS(string siteName) {     return Process.Start(@"C:\Program Files (x86)\IIS Express\iisexpress.exe", $"/site:{siteName} /config:{_applicationHostConfigFilePath}"); } 

The errors only occur on some machines, and we can't figure out what is configured differently between them. I've tried using Chrome's --disable-web-security flag but it doesn't seem to make any difference.

2 Answers

Answers 1

You can usually solve pre-flight errors with a change to your web.config:

<system.webServer>      ...  <httpProtocol>     <customHeaders>         <add name="Access-Control-Allow-Origin" value="*" />         <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Cache-Control" />         <add name="Access-Control-Allow-Credentials" value="true" />         <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />     </customHeaders> </httpProtocol> </system.webServer> 

Or via code in a custom handler with something like:

if (request.Headers.Contains("Origin") && request.Method.Method == "OPTIONS") {     var response = new HttpResponseMessage();     response.StatusCode = HttpStatusCode.OK;     response.Headers.Add("Access-Control-Allow-Origin", "*");     response.Headers.Add("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization");            response.Headers.Add("Access-Control-Allow-Methods", "DELETE, POST, PUT, OPTIONS, GET"); } 

If it works you can then try refining things by e.g. changing Access-Control-Allow-Origin to just your front-ends address.

Answers 2

Assuming you are using windows OS. If yes then, did you allow your application to bypass windows firewall..? ex: if you have a application running on localhost:9000, then you need to make sure windows firewall has rules to allow port 9000.

Hope, this resolves your issue.

Read More

Thursday, September 13, 2018

Owin SelfHost WebApi - client closing the connection during response raises an exception?

Leave a Comment

I'm running an Owin Selfhost based WebApi where i've put in an API unhandled exception logger via

config.Services.Add(typeof(IExceptionLogger), _apiExceptionLogger); 

Relevant part of ApiExceptionLogger:

    public override void Log(ExceptionLoggerContext context)     {         if (context == null || context.ExceptionContext == null) return;          Logger.Error("Unhandled exception from Web API", context.ExceptionContext.Exception);     } 

The cases it's catching and logging regularly are ones where the client requests a dataset and then closes the connection while the results (JSON) are being sent back - people making a request in chrome, and then hitting the X button before all results come back :P

I've pasted a stacktrace below for completeness, just want to know two things:

  • Is this regular/expected behavior? AFAIK it is...I'm running a pretty default API and pipeline
  • Is there any way to handle this? Essentially stop request processing more gracefully in case of a cancellation (the cancellation tokens peppered throughout the request pipeline do come to mind, but doesn't look like they do much in this case, after all the tokens only support co-operative cancellation)

I haven't done any deep dive on the sequence of events happening at the socket level, so far this is only a logging nuisance.

System.Net.Http.HttpRequestException: Error while copying content to a stream. ---> System.IO.IOException ---> System.Net.HttpListenerException: The I/O operation has been aborted because of either a thread exit or an application request    at System.Net.HttpResponseStream.EndWrite(IAsyncResult asyncResult)    at Microsoft.Owin.Host.HttpListener.RequestProcessing.ExceptionFilterStream.EndWrite(IAsyncResult asyncResult)    --- End of inner exception stack trace ---    at Microsoft.Owin.Host.HttpListener.RequestProcessing.ExceptionFilterStream.EndWrite(IAsyncResult asyncResult)    at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)    --- End of inner exception stack trace ---    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at System.Web.Http.Owin.HttpMessageHandlerAdapter.<SendResponseContentAsync>d__20.MoveNext()    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at System.Web.Http.Owin.HttpMessageHandlerAdapter.<SendResponseContentAsync>d__20.MoveNext() 

2 Answers

Answers 1

I had a similar issue with Owin host on Raspberry Pi. This may help https://stackoverflow.com/a/30583109/1786034

Answers 2

Its code issue

Read file async and check.At any time if you are doing an api call and it times out it will definitely throw exception.

using (StreamReader reader = new StreamReader(await selectedFile.OpenStreamForReadAsync()))             {                 while ((nextLine = await reader.ReadLineAsync()) != null)                 {                     contents.AppendFormat("{0}. ", lineCounter);                     contents.Append(nextLine);                     contents.AppendLine();                     lineCounter++;                     if (lineCounter > 3)                     {                         contents.AppendLine("Only first 3 lines shown.");                         break;                     }                 }             } 
Read More

Monday, July 16, 2018

Background timer task .net Web Api and Xamarin form

Leave a Comment

I have been working on a xamarin form app. The primary purpose of the app is to let user create a count down timer and if user doesn't stop the timer before it reaches zero then it sends SMS messages to some numbers.

I am using android foreground service to start a timer and display a count down timer. It is working fine, however, this solution is not 100% reliable as SMS will not be sent if for some reason phone is shut down after the timer has stared. Therefore, I would like to move the timer logic to .Net Web API (my app is already using .Net Web API for other functionality) so that when a user starts the timer, Web API on the server tracks the timer for the user who started the timer.

Can someone guide me to implement a reliable solution for web api for above scenario? I have looked at Hangfire and other scheduled tasks such as windows service but those seem too complicated for this seemingly easier task. The timer needs to be started and stopped dynamically via Web API and if it reaches zero then "SendSMS" method in Web API needs to be called.

2 Answers

Answers 1

You can use this example or other similar to send sms and implement the countdown timer on the web service side.

then you use HTTPClient class on Xamarin to inform the web service that the timer needs to be started or stoped.

Let me know if you need a code example.

Answers 2

You can take the advantage from System.Threading.Tasks Assembly.Like this

 CancellationTokenSource tokenSource;          private void CancelSendMessageTask()         {             tokenSource?.Cancel();         }          private void StartTimer()         {             int SecondsToWait = 90;             tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(SecondsToWait));              Task.Delay(TimeSpan.FromSeconds(SecondsToWait), tokenSource.Token).ContinueWith((t) =>             {                 if (t.IsCanceled) return;                 SendSMS();             });         } 
Read More

Friday, June 29, 2018

Asp.net WebApi OData V4 problems with nested $expands

Leave a Comment

I have a OData V4 over Asp.net WebApi (OWIN).

Everything works great, except when I try to query a 4-level $expand.

My query looks like:

http://domain/entity1($expand=entity2($expand=entity3($expand=entity4))) 

I don't get any error, but the last expand isn't projected in my response.

More info:

  1. I've set the MaxExpandDepth to 10.
  2. All my Entities are EntitySets.
  3. I'm using the ODataConventionModelBuilder.
  4. I've opened an SQL-profiler and could see that the query (and the result) is correct. It's some filter that occurs after the query is executed.
  5. I've searched the web and didn't find anything suitable.
  6. I've tried different entity 4 level $expands and they didn't work as well.

Edit:

I've overridden the OnActionExecuted:

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {     base.OnActionExecuted(actionExecutedContext);      var objectContent = actionExecutedContext.Response.Content as ObjectContent;     var val = objectContent.Value;      var t = Type.GetType("System.Web.OData.Query.Expressions.SelectExpandWrapperConverter, System.Web.OData");     var jc = Activator.CreateInstance(t) as JsonConverter;     var jss = new JsonSerializerSettings();     jss.Converters.Add(jc);      var ser = JsonConvert.SerializeObject(val, jss);  } 

The serialized value contains entity4.

I still have no idea what component removes entity4 in the pipe.

Edit #2:

I've create an adapter over DefaultODataSerializerProvider and over all the other ODataEdmTypeSerializer's. I see that during the process the $expand for entity4 exists and when the ODataResourceSerializer.CreateNavigationLink method is called on that navigationProperty (entity4) then it returns null.

I've jumped into the source code and I could see that the SerializerContext.Items doesn't include the entity4 inside it's items and the SerializerContext.NavigationSource is null.

To be specific with versions, I'm using System.Web.OData, Version=6.1.0.10907.

0 Answers

Read More

Monday, June 4, 2018

error when url resource contains ampersand

Leave a Comment

We have a web api with the following resource url.

http://www.example.com/book/bookid/name/bookname 

now there are some books which contains names with ampersand '&' and when a request is made for such names, we are receiving below error

URL used:

http://www.example.com/book/123/name/ban&ban 

Error: A potentially dangerous Request.Path value was detected from the client (&)

We tried passing or using encoded value for & i.e. %26 and getting same error.

URL used:

http://www.example.com/book/123/name/ban%26ban 

Error: A potentially dangerous Request.Path value was detected from the client (&)

Now, when I added requestPathInvalidCharacters="" property in the web.config in httpruntime element, it started working fine for both the above urls. But, when I read different articles, it is said that it is not a good practice to use requestPathInvalidCharacters="" property.

Also, since there are lot of book names in production with "&" and different special characters, we cannot avoid sending "&" ampersand for book names, is there a good way to handle this?

1 Answers

Answers 1

You should opt into using parameter instead of path in your querystring. For example: http://www.example.com/book/bookid?name=Fizz&bookname=Buzz

Here's some explanation on why this exception is raised: http://www.hanselman.com/blog/ExperimentsInWackinessAllowingPercentsAnglebracketsAndOtherNaughtyThingsInTheASPNETIISRequestURL.aspx

Read More

Wednesday, May 23, 2018

Make Web API authentication return 401 instead of redirect to login page

Leave a Comment

I have Web API with OWIN Authentication in Web MVC. I'm using <authentication> in Web.Config for my Web MVC so it's redirecting to login page.

<authentication mode="Forms">     <forms name="WEB.AUTH" loginUrl="~/login" domain="" protection="All"      timeout="43200" path="/" requireSSL="false" slidingExpiration="true" /> </authentication> 

I'm using [System.Web.Http.Authorize] attribute to authorize my Web API. But somehow, the API redirecting to login page same like my MVC app because of above configuration.

what I want to do is keep redirecting function for the Web MVC but returning 401 for Web API. How can I achieve this? should I create a custom authorization attribute for Web API?

--EDIT--

I found the answer from this post SuppressDefaultHostAuthentication in WebApi.Owin also suppressing authentication outside webapi

So I just add a few lines into my Startup.cs. I had all my controllers configured with a "api" prefix route.

HttpConfiguration config = new HttpConfiguration(); //..some OWIN configuration app.Map("/api", inner => {   inner.UseWebApi(config); }); 

make sure you put app.Map() after Web Api Configuration lines. Otherwise, it will give error to MVC application.

3 Answers

Answers 1

Create a custom AuthorizeAttribute:

public class MyAuthorizeAttribute : AuthorizeAttribute {     protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)     {         actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized");     } } 

If you in the future skip the web.config stuff and use owin to setup your authentication, you could in your Startup.cs do:

var provider = new CookieAuthenticationProvider(); var originalHandler = provider.OnApplyRedirect; provider.OnApplyRedirect = context => {     if (!context.Request.Uri.LocalPath.StartsWith(VirtualPathUtility.ToAbsolute("~/api")))     {         context.RedirectUri = new Uri(context.RedirectUri).PathAndQuery;         originalHandler.Invoke(context);     } };  app.UseCookieAuthentication(new CookieAuthenticationOptions {     AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,     CookieName = FormsAuthentication.FormsCookieName,     LoginPath = new PathString("/Account/LogOn"),     ExpireTimeSpan = TimeSpan.FromMinutes(240),     Provider = provider }); 

Answers 2

This is what worked for me.

Creating a custom attribute:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class NoRedirectAuthorizeAttribute : AuthorizeAttribute {             protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)     {         actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);     } } 

Using the attribute in your controller:

    [HttpDelete]     [NoRedirectAuthorizeAttribute(Roles = "Admin")]     [Route("api/v3/thingstodelete/{id=id}")]     public IHttpActionResult DeleteThingToDelete(Guid id)     {       //delete code     } 

Here are just overriding the HandleUnauthorizedRequest method of the AuthorizeAttribute. So, instead of sending a redirect (304) to the login page, we send Forbidden(403) HTTP status code.

Answers 3

In order to change the way IIS behaves based on a convention defined by URL, you want to branch your OWIN pipeline. You can do this by using IApplicationBuilder.Map. Assuming a static config:

public void Configure(IApplicationBuilder app) {     ...     app.Map("/api", HandleWebApiRequests);     ... }  private static void HandleWebApiRequests(IApplicationBuilder app) {     app.UseWebApi(config); } 

The Map method branches the pipeline to the HandleWebApiRequests method based on an URL that begins with "/api".

This should cause 401 errors to behave like they are supposed to and simply return 401 with no redirect.

Read More

Sunday, February 11, 2018

Application Architecture - Monolith to Distributed/SOA

Leave a Comment

I have experience creating web applications using MS Asp.Net Stack (Asp.Net MVC / Web API), using 3-tier architecture (Monoliths)

I want to learn how to make applications scalable and maintainable, and want to clarify certain confusions with buzz-words.

  1. Distributed vs. SOA - I believe a scalable/maintainable application means segregating service layers (persistence, security, caching, etc.), and moving them to separate tiers. This is advocated by both distributed and SOA, so what's the difference b/w two?
  2. Service implementation, deployment and management - How to do it practically? I sense 2 types of services exist - Active and Passive.
  3. Passive Services - These kinds of services are essentially functions/methods that can be called to perform some operation. They can be implemented as WCF or Web API. With say 10 such services in hand, how do we implement, deploy (host) and manage them? How to know if any of service host goes down or malfunctions?
  4. Active Services - These kinds of services are active executables, and might be listening to a message-broker to fetch queued work. So, again, with say 10 such services in hand, how do we implement, deploy (host) and manage them? Do we create separate window services for each?
  5. Service Communication - with services segregated to different tiers, how to decide if they should communicate synchronously (web api) or asynchronously through message-broker (pub-sub)?

2 Answers

Answers 1

Here my perspective. Before I get to your questions let me address the general conception of monolith vs microservice: The difference lies in how the code is separated and what the goal is. For a monolith you try to apply techniques that aim to make it possible for a very large team (say 100s of engineers) to work on a single code base for an application. This means the introduction of layers and a lot of abstraction work typically to separate modules. And sometimes there is a lot of over-engineering in the design to promote reuse and separate layers at the same time. Usually it is easy for new employees to mess something up or not adhere to the complex architecture. Additionally there is often a large graph of dependencies between modules. The microservices philosophy now comes and tries to enforce modularity by having separate teams responsible for different services and not allowing them to share data persistency. In other words it tries to address the issues stemming from "Architecture follows Organization" (Conway's Law) by organizing teams by architecture and not the other way round. From my personal experience this is very fundamental to many issues in large organizations developing software and something that people often misunderstand when someone uses the buzzword microservices. For more information I recommend reading the works of Fowler. So the technology (.Net, Java, golang, etc.) does not play as much a role and the traditional "tiering" of services is an architectural decision that is still relevant but has to be seen less from a perspective of monolithic tiers but rather as tiers of clustered, scalable services (more about that below).

So now to your questions:

  1. Distributed vs. SOA: These are different viewing angles onto architecture and only intersect with the difference of monolith vs microservices in that a distributed architecture promotes techniques that are relevant for the devops required to build, test, deploy and scale (micro)services. And a SOA does not imply a monolith or microservices in itself. Simplified it just promotes the usage of clearly defined APIs and standardization of communication protocols between services. Some people also imply self-containment, which in this case the overlap to the microservices intention is larger. But others call the front services that their monolith provides also SOA. So you always have to look into the details.

  2. Service implementation, deployment and management. Beside the buzzwords there are a few actually useful techniques that are relevant here: Containerized applications (see Docker), which then enable clustered, orchestrated deployment (see kubernetes), which in combination with stateless application containers allow seamless scalability of services (see auto-scaling). Additionally scalable databases are coming more and more into the picture (see cockroachdb and various NoSQLs). And everything can be automated / tested / controlled from CICD servers (continuous integration / continuous deployment) - See Jenkins for example. All these make large application deployments so much easier and also allow for zero-outage updates if done right (see the topic of rolling updates). A cluster system will also typically contain functionality to detect the application health (for example endpoint testing). Unhealthy containers can be excluded from servicing client requests and replaced in an automated fashion by the container orchestration system.

  3. and

  4. Active/Passive Services: This distinction is not quite as useful. In the world of clusterized applications you think of each deployed application as a server providing services (usually formalized in a deployment description) or as a simple task/workload without services. But each may have dependencies to the outside world. In other words each deployed application could be active/passive or both but all will have some executable portion. I recommend looking into how a deployment is formalized with kubernetes for example.

  5. Communication: Typically most communication will be asynchronous with the caveat that the service implemention often includes techniques to allow for treating an asynchronous call almost as if it was synchronous in the code (e.g. promises, observables). This is due to the fact that humans cannot think asynchronously very well.

Let me know if that answers some of your questions or if it only adds to the confusion.

Answers 2

Some of the very basic requirement for transitioning a monolith service to a distributed service is:

Get rid of the state in your application. By this I mean you should avoid having static fields & any information which is restricted to a single JVM. Rather move out all the information which specific servers are holding to a central memory like HazelCast or Memcache. So that all your servers share common information. This will enable your app to be consistent when any of your server goes down.

The same rule holds good when using sessions. Move all the sessions to a central memory.

P.S. I work on Java Stack so you can look for similar .NET tech.

Moving down to your questions

  1. Distributed vs. SOA : The difference between the two is very subtle. A Service Oriented Architecture means there are several independent services running with respective responsibilities. They are all components of a single application. Read about Web Services. For an instance Billing can be one service. Booking Tickets can be another service working in conjunction. SOA makes the system more manageable.

Distributed means splitting/partitioning a service into multiple chunks to achieve scalability & availability. Now this concept can be applied both at a higher level or on individual services in the SOA. The service runs on several nodes/servers. If one node goes down the entire Billing service doesn't go down.

  1. Service implementation, deployment and management: A distributed system ideally runs on cloud. Go through Google Cloud & Amazon Cloud docs. You'll get an understanding how the entire flow works. Also read about SQL vs NOSQL. CAP Theorem. ACID vs BASE. Can't write everything here. The answer will become humongous.

  2. Active/Passive Services: Stated above cloud docs. will help you get an understanding about these services. Also look into Zookeeper.

  3. Service Communication: Communicating synchronously or asynchronously entirely depends upon the application design. You would require a messaging service like RabbitMQ or Kafqa if you are communicating with other services.

You have a lot to read. GoodLuck :)

Read More

Monday, January 8, 2018

How to log file contents in request body of a multipart/form-data request

Leave a Comment

I am trying to log all requests in my asp.net web API project to a text file. I am using DelegationHandler feature to implement logging mechanism in my application, below is the code snippet for that,

public class MyAPILogHandler : DelegatingHandler     {         protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)         {            // Captures all properties from the request.             var apiLogEntry = CreateApiLogEntryWithRequestData(request);             if (request.Content != null)             {                     await request.Content.ReadAsStringAsync()                         .ContinueWith(task =>                         {                             apiLogEntry.RequestContentBody = task.Result;                         }, cancellationToken);             }              return await base.SendAsync(request, cancellationToken)                 .ContinueWith(task =>                 {                     var response = task.Result;                      // Update the API log entry with response info                     apiLogEntry.ResponseStatusCode = (int)response.StatusCode;                     apiLogEntry.ResponseTimestamp = DateTime.Now;                      if (response.Content != null)                     {                         apiLogEntry.ResponseContentBody = response.Content.ReadAsStringAsync().Result;                         apiLogEntry.ResponseContentType = response.Content.Headers.ContentType.MediaType;                         apiLogEntry.ResponseHeaders = SerializeHeaders(response.Content.Headers);                     }                         var logger = new LogManager();                     logger.Log(new LogMessage()                     {                        Message = PrepareLogMessage(apiLogEntry),                        LogTo = LogSource.File                     });                      return response;                 }, cancellationToken);         } } 

Above implementation is working as expected and it is logging all required request/response information to the file.

But when we make any multipart/form-data POST api call with some images attached, after logging this request, log file becomes huge, because all image/binary content is getting converted into string and writing down it the text file. please find below log file content,

Body:  ----------------------------079603462429865781513947 Content-Disposition: form-data; name="batchid"  22649EEE-3994-4225-AF73-D9A6B659CAE3 ----------------------------079603462429865781513947 Content-Disposition: form-data; name="files"; filename="d.png" Content-Type: image/png  PNG   IHDR    í   %v ¸   sRGB ®Îé   gAMA  ±üa      pHYs  à  ÃÇo¨d  ÿ¥IDATx^ìýX]K¶( ·îsß»ß÷þï{O÷iÛ    Á2âîîîÁe¹âîî,<@   Á$÷w_ÈZó5$Dwvv×} ----------------------------4334344396037865656556781513947 Content-Disposition: form-data; name="files"; filename="m.png" Content-Type: image/png  PNG   IHDR    í   %v ¸   sRGB ®Îé   gAMA  ±üa      pHYs  à  ÃÇo¨d  ÿ¥IDATx^ìýX]K¶( ·îsß»ß÷þï{O÷iÛ    Á2âîîîÁe¹âîî,<@   Á$÷w_ÈZó5$Dwvv×} 

I don't want to log the binary content of a request body, it could be sufficient to log only request body file contents like,

    ----------------------------079603462429865781513947     Content-Disposition: form-data; name="batchid"      22649EEE-3994-4225-AF73-D9A6B659CAE3     ----------------------------079603462429865781513947     Content-Disposition: form-data; name="files"; filename="d.png"     Content-Type: image/png      ----------------------------4334344396037865656556781513947     Content-Disposition: form-data; name="files"; filename="m.png"     Content-Type: image/png 

Can you please suggest how to prevent logging binary content of request body and log only file contents of a request body.

2 Answers

Answers 1

From what I gather, you are implementing something similar to this approach. When uploading a file (i.e., a request type "multipart/form-data") its actual content always begins with the "Content-Type: {ContentTypeValue}\r\n\r\n" sequence and the next header begins with "\r\n--" sequence (as it is illustrated in your logs). You can explore more info about raw request data parsing at ReferenceSource. So, you can strip everything about file (if exists), for example, via RegEx:

Content-Type: {ContentTypeOrOctetStream}\r\n\r\n{FileContentBytesToRemove}\r\n

using System.Text.RegularExpressions; ... string StripRawFileContentIfExists(string input) {     if(input.IndexOf("Content-Type") == -1)         return input;     string regExPattern = "(?<ContentTypeGroup>Content-Type: .*?\\r\\n\\r\\n)(?<FileRawContentGroup>.*?)(?<NextHeaderBeginGroup>\\r\\n--)";     return Regex.Replace(input, regExPattern, me => me.Groups["ContentTypeGroup"].Value + string.Empty + me.Groups["NextHeaderBeginGroup"].Value); } ... //apiLogEntry.RequestContentBody = task.Result; apiLogEntry.RequestContentBody = StripRawFileContentIfExists(task.Result); 

Answers 2

I'd suggest separate huge content from log. like you encountered, it just screws everything up in the log. to some extent disables log functionality.

I'd suggest you organize those huge content in file system. like this:

---request-a/   |--request-a-body-multi-part1.txt   |--request-a-body-multi-part2.txt 

and just maintain a link in your log to reference this file system path.

hope it helps.

Read More

Thursday, December 28, 2017

Swagger does not show real error message

Leave a Comment

We are on .NET WebAPI framework and we are using swagger on top of web api for annotations and out of the box UI experience. So far, it just has been working great. However, when I return an error from WebAPI(Http 400) as following code:

return BadRequest("Some error");

However, when I do that, it seems like Swagger is not able to parse the error properly. It basically, show response 0. Which is wrong for sure because when I go to Chrome DevTools, I see that my request had a response of HTTP 400 as I expected.

How can I configure Swagger so that it is able to show the errors correctly? Or should I be throwing my errors a little bit differently to be able to see it in swagger?

1 Answers

Answers 1

You can annotate your actions like this

[ProducesResponseType(typeof(ResponseObjectTypeHere), 200)] [ProducesResponseType(typeof(ErrorResponseObjectTypeHere), 400)] 

You can also add something like this in the xml documentation if you enable swagger to read and use xml documentation

/// <response code="200">Description</response> /// <response code="400">Description of error</response> 

I used those in the .net core web api project with swagger, should be the same for regular .net web api project as well.

Read More

Wednesday, November 8, 2017

Rewriting the Url with POST data in the Application_AquireRequestState event

Leave a Comment

I have a code which registers the route in Application_AcquireRequestState event of the application. Once the routes are registered, I set a flag in the Http runtime cache so that I don't execute the route registration code again. There is a specific reason to register the route in this event Application_AcquireRequestState.

Once the app pool is restarted and if a valid(matching the route) request comes in, the route registration code kicks in but that request is not served by IIS/ASP.Net and it returns 404. The subsequent valid requests are all working fine.

I want to make sure even the first request is also served correctly.

Is it possible to rewrite the request so that after the route registration is done we can somehow try to replay the request if the url matches with one of the route that are registered? Is there any solution to solve this problem?

1 Answers

Answers 1

This is a kind of pseudocodewhich you can use in Global.asax.

private bool RootIsRegistered = false; //register Application level var  void Application_BeginRequest(object sender,EventArgs e){    if(!RootIsRegistered)       RegisterRoots(); } 

This way you can be sure that your roots are registered even at the first request.

Read More

Sunday, November 5, 2017

Cookies visible from HttpResponseMessage but not in Javascript

Leave a Comment

I have a login service which passes user login information to my application when I login. This will call first page of my application on successful login. The user info is passed as part of a cookie in this request.

I am trying to read these cookies from the request in my Web API request using the below code.

 CookieHeaderValue getAccessUserInfo = request.Headers.GetCookies("GAUSERINFO").FirstOrDefault();                  if (getAccessUserInfo != null)                 {                     userInfo = getAccessUserInfo["GAUSERINFO"].Values.Get("corporate_id");                     Logger.Info(string.Format("User Cookie {0}", userInfo));                     return userInfo;                 } 

But if I am trying to read the same cookie from javascript or angular js, I am not able to see that cookie in the collection. Below is the code I am using to read the cookie in angular js.

console.log($document[0].cookie); 

This is the cookie I can see from the result. The cookie I am expecting is GAUSERINFO along with the below cookies.

enter image description here

Is there a way to read these cookies from angular js or atleast pass that request body to the API so that I can read the cookie in my API using C# code.

1 Answers

Answers 1

JavaScript doesn't have access to HTTP only cookies for security reasons. In order to prevent XSS attacks, generally user session/login information should be HTTP only. If an attacker were to get the user's session information, they could impersonate the user. If you want to expose user info like corporate_id to the client side, it can be in a separate cookie that is not marked as HttpOnly.

From MSDN for HttpCookie.HttpOnly:

Stolen cookies can contain sensitive information identifying the user to the site, such as the ASP.NET session ID or forms authentication ticket, and can be replayed by the attacker in order to masquerade as the user or obtain sensitive information. When an HttpOnly cookie is received by a compliant browser, it is inaccessible to client-side script.

To use corporate_id client side, create a separate cookie with the only the information you need client side and when you create it in your C# code be sure to set HttpOnly to false.

Edit: If your use case is to forward the cookie along to your API using Angular's $http service, there's additional configuration you can do for it which is detailed in this answer: https://stackoverflow.com/a/17065576/6950124

The summary of it being that you need to set $httpProvider.defaults.withCredentials = true; and potentially also configure your web server to send back the header Access-Control-Allow-Credentials: true when the browser initially requests the page. This lets the browser know that your JavaScript code can have partial access to the HttpOnly cookies.

The underlying browser code for making the AJAX call should forward HttpOnly cookies if you have everything configured properly.

Read More

Wednesday, November 1, 2017

CORS Options Preflight Hanging

Leave a Comment

I have a ASP Web API project that is being hosted over SSL. I have another ASP MVC project that makes use of the API. While debugging, I am seeing behavior where the OPTIONS requests are hanging often (but not always) and preventing the other calls from proceeding.

In the Chrome debugger, these are just shown as 'Pending'. If launch Fiddler, everything works fine. I see no errors at all, things just hang. This fails before it hits the authorization code, so I can't even set any breakpoints.

Could this be a certificate problem? Firewall?

1 Answers

Answers 1

Could you try this: adding following node in web.config.

<system.webServer>     <handlers>          <!-- your other handlers -->          <remove name="OPTIONSVerbHandler" />     </handlers> </system.webServer> 
Read More

Tuesday, October 24, 2017

Using OData in .NET Core Web API for MongoDB

2 comments

OData is now supported in .NET Core and 7.2.0 was released. But can it be used with MongoDB? I have searched, but I could not find anything that says one way or the other.

EDIT:

I've found a nuget package https://www.nuget.org/packages/microsoft.aspnetcore.odata and in ConfigureServices I've added this:

And this seems to work for me:

public void ConfigureServices(IServiceCollection services) {     ...     services.AddOData();     services.AddSingleton<IODataModelManger, ODataModelManager>(DefineEdmModel);     ... }  private ODataModelManager DefineEdmModel(IServiceProvider services) {     var modelManager = new ODataModelManager();      var builder = new ODataConventionModelBuilder();     builder.EntitySet<TestDTO>(nameof(TestDTO));     builder.EntityType<TestDTO>().HasKey(ai => ai.Id); // the call to HasKey is mandatory     modelManager.AddModel(nameof(Something), builder.GetEdmModel());      return modelManager; } 

Controller

[HttpGet("all")] public async Task<IQueryable<TestDTO>> Get() {     // plug your entities source (database or whatever)     var test = await TestService.GetTest();      var modelManager = (IODataModelManger)HttpContext.RequestServices.GetService(typeof(IODataModelManger));     var model = modelManager.GetModel(nameof(Something));     var queryContext = new ODataQueryContext(model, typeof(TestDTO), null);     var queryOptions = new ODataQueryOptions(queryContext, HttpContext.Request, Provider);      return queryOptions         .ApplyTo(test, new ODataQuerySettings         {             HandleNullPropagation = HandleNullPropagationOption.True         }, null)         .Cast<TestDTO>(); } 

Service

public async Task<IQueryable<TestDTO>> GetTest() {     return await GenericRepository.TestAll(); } 

Repositories

public async Task<IQueryable<TEntity>> TestAll() {     var res = new GetManyResult<TEntity>();     try     {         DateTime startTime = DateTime.Now;         var collection = GetCollection<TEntity>().AsQueryable();         var entities = collection.ToArray<TEntity>().AsQueryable();         return entities } 

But is this the best way to do it?

I mean, shouldn't the collection contain only the elements that meet the filters, beeing more optimised?

If yes, how do I achieve this?

1 Answers

Answers 1

I think theres only currently one connected service available in the visual studio market place for MongoDB. Link Here.

ODBC Driver for MongoDB provides high-performance and feature-rich connectivity solution for ODBC-based applications to access MongoDB databases from Windows, MacOS, Linux. Full support for standard ODBC API functions, MongoDB data types and SQL queries implemented in our driver makes interaction of your database applications with MongoDB fast, easy and extremely handy.

Looks like it would handle all of the things you'd expect it to when connecting to MongoDB.

However it's worth noting that, that is only a trail and I've been unable to find any 'open source' versions

Read More

Wednesday, September 20, 2017

REST API not working with MySQL

Leave a Comment

I am creating a REST API using MySQL DB in visual studio 2015 in asp.net mvc 4.5. I have done each and every step which in needed to run the API using MySQL, but I am getting this exception.

{"Message":"An error has occurred.","ExceptionMessage":"Format of the initialization string does not conform to specification starting at index 121.","ExceptionType":"System.ArgumentException","StackTrace":" at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue)\r\n at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey)\r\n at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules)\r\n at System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String value)\r\n at MySql.Data.MySqlClient.MySqlConnectionStringBuilder..ctor(String connStr)\r\n at MySql.Data.MySqlClient.MySqlConnection.set_ConnectionString(String value)\r\n at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.b__18(DbConnection t, DbConnectionPropertyInterceptionContext1 c)\r\n at System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action2 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed)\r\n at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.SetConnectionString(DbConnection connection, DbConnectionPropertyInterceptionContext1 interceptionContext)\r\n at System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection)\r\n at System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config)\r\n at System.Data.Entity.Internal.LazyInternalConnection.Initialize()\r\n at System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel()\r\n at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()\r\n at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)\r\n at System.Data.Entity.Internal.Linq.InternalSet1.Initialize()\r\n at System.Data.Entity.Internal.Linq.InternalSet1.GetEnumerator()\r\n at System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()\r\n at System.Collections.Generic.List1..ctor(IEnumerable1 collection)\r\n at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)\r\n at RestWithMySQL.Controllers.ProductsController.Get() in D:\Work\DOT NET API\RestWithMySQL\RestWithMySQL\Controllers\ProductsController.cs:line 19"}

I think there is a problem in my connection string. I have searched for it but couldn't find the exact solution.

<connectionStrings>     <!--<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-RestWithMySQL-20170911031521.mdf;Initial Catalog=aspnet-RestWithMySQL-20170911031521;Integrated Security=True" providerName="System.Data.SqlClient" />-->     <add name="ProductEntities" connectionString="metadata=res://*/ProductsModel.csdl|res://*/ProductsModel.ssdl|res://*/ProductsModel.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot; server=localhost;user id=root;database=accurate_dev;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="MySql.Data.MySqlClient"/>     <!--<remove name="LocalMySqlServer" /><add name="LocalMySqlServer" connectionString="" providerName="MySql.Data.MySqlClient" />--> </connectionStrings> 

Any help would be highly appreciated.

3 Answers

Answers 1

Strip down your connection string to the bare minimum. Add options back and see what causes it to fail. For example integrated security=true is not going to work with MySQL. You will need to add a password instead.

Form here: ASP.NET MVC 4 EF5 with MySQL

Try something closer to this:

<add name="DefaultConnection" providerName="MySql.Data.MySqlClient" connectionString="Data Source=localhost;port=3306;Initial Catalog=api_db;User Id=root;password=''"/>

Answers 2

Shouldn't your connection string have another quote in it at the end?

<connectionStrings>     <add name="ProductEntities" connectionString="metadata=res://*/ProductsModel.csdl|res://*/ProductsModel.ssdl|res://*/ProductsModel.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot; server=localhost;user id=root;database=accurate_dev;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="MySql.Data.MySqlClient"/> </connectionStrings> 

Further: In order to use the MySQL provider, consider these steps provided in this answer

Answers 3

You are missing a closing &quot; at the end of your connection string.

Read More

Saturday, September 16, 2017

web api get is working but post and delete not working after published in iis

Leave a Comment

I've been struggling for 4 hours and I still didn't get any solution. I already apply some modification but still my post and delete api returns the error 500.

GET js

$.getJSON(API_URL + 'api/claim/search', params).done(function (data) {     myJsonObject = data;     d.resolve(data); }); return d.promise(); 

API

[Route("api/claim/search")] [System.Web.Http.AcceptVerbs("GET")] [System.Web.Http.HttpGet] public IEnumerable<ClaimInfo> Get([FromUri] ClaimSearch obj_ClaimSearch) {     //my code } 

This get method is working 100%

POST js

$.ajax({     type: "POST",     data: JSON.stringify(p[0]),     url: API_URL + "api/claim/" + (editorPage === "resubmission" ? "saveresubmissionpatient": "savepatient"),     contentType: "application/json",     success: function (data) {      },     error: function () {      } }); 

API

[Route("api/claim/savepatient")] [System.Web.Http.AcceptVerbs("POST")] [System.Web.Http.HttpPost] public Guid SavePatient([FromBody]ClaimInfo claimInfo) {     //my code } 

And here is my WebApi.Config.cs

public static void Register(HttpConfiguration config) {     config.MapHttpAttributeRoutes();      config.Routes.MapHttpRoute(         name: "DefaultApi",         routeTemplate: "api/{controller}/{id}",         defaults: new { id = RouteParameter.Optional }     );  } 

I already apply this webserver thing in my config

<modules>   <remove name="WebDAVModule" />   <add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v16.2, Version=16.2.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule" /> </modules> <handlers>   <remove name="WebDAV" />   <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />   <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />   <remove name="ExtensionlessUrlHandler-Integrated-4.0" />   <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />   <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />   <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />  </handlers> 

2 Answers

Answers 1

I had a similar issue, and it had to do with the name of the function catching the request. For some reason, GET functions did this automatically but POST did not always do so. You could try explicitly naming it like this, and see if it also solves your problem:

[Route("api/claim/savepatient")] [System.Web.Http.AcceptVerbs("POST")] [System.Web.Http.HttpPost, ActionName("SavePatient")] public Guid SavePatient([FromBody]ClaimInfo claimInfo) {     //my code } 

Note that I changed [System.Web.Http.HttpPost] to [System.Web.Http.HttpPost, ActionName("SavePatient")]

Answers 2

You have named the action "savepatient" instead of Post. The router matches /api/{controller} to your {controller}Controller Class. The HTTP method must match the public method of the class. Try renaming "SavePatient" to "Post" (or "Put" if you use that method).

public class ClaimController : ApiBaseController { //[Route("api/claim/")] don't need this public Guid Post([FromBody]ClaimInfo claimInfo) {     //my code to add new claiminfo } //[Route("api/claim/")] don't need this public Guid Put([FromBody]ClaimInfo claimInfo) {     //my code to edit claiminfo } 

And remove the extra path on the url:

url: API_URL + "api/claim/" 
Read More

Wednesday, August 30, 2017

Go To Controller shows “Unable to find a matching controller.” error

Leave a Comment

In VS 2015, for my Web.API project, I installed MVC 5 from nuget via npm. This installation added references and generated web.config file under Views folder.

I added new Controller with generated CRUD functions. When I right click and go to View on action it goes with no problem. But reverse action does not work. If I navigate to view via browser it works as well. Web app compiles as well.

Is there any way for me to fix this navigation problem in VS? Did I forget to add something?

Following Works

this works with no problem

Following gives Error:

this does not work

error

P.S: If I create brand new sample MVC 5 app both actions work as expected, this only happens Web.API project where MVC 5 added later on via nuget.

4 Answers

Answers 1

This happened to me once. Delete the view and try adding the view again by right clicking on the controller action method and clicking Add View again. I think it would solve the problem

Answers 2

There appears to be a default shortcut key Ctrl-M then Ctrl-G.

This will automatically switch between the controller and view page. If you're on the controller/action it will switch to the view and vice versa.

Answers 3

It happens while the controller or view may be not exactly in the controller folder or view folder respectively. It may contain an additional folder. You can solve this issue through adding a new view and delete the old view.

Answers 4

YOU can try it like this, Add Controller first ,then and the View By hands,then you can get the right page what you want ?

Read More

Thursday, August 3, 2017

My web api gives net:: ERR_CONNECTION_RESET error only from ajax client

Leave a Comment

My web api was working in several IISs and when moved to Azure VM, it gives net:: ERR_CONNECTION_RESET when calling only from ajax client but works proper when using POSTMAN.

When hitting from ajax html client it says net:: ERR_CONNECTION_RESET in OPTIONS request. Thought that it didnt reach the server but when referring http error file in

C:\Windows\System32\LogFiles\HTTPERR

It shows

2017-07-20 12:54:06 210.18.173.26 54141 10.0.1.4 80 HTTP/1.1 OPTIONS /api/User/Method1 - 1 Request_Cancelled myappapipool

In web.config

 <add name="Access-Control-Allow-Origin" value="*" />  <add name="Access-Control-Allow-Headers" value="Content-Type" />  <add name="Access-Control-Allow-Credentials" value="true" />  <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" /> 

I have tried adding timeout in web.config, it is not solving. Also tried changing the web config "Access-Control-Allow-Headers" value to "*", it gave preflight request error.

Since the same server and ajax client communication is working in other iis, i suspect there is something fishy which i missing while configuring my web api in IIS which is located in Azure VM. When calling from POSTMAN or android client it is working like a charm with the existing configuration in IIS.

Any help/suggestion is much appreciated.

4 Answers

Answers 1

Request_Cancelled Coming in HTTPErr log is caused by the DynamicIPRestrictions Module mitigating against DDOS attacks.

if you setup Dynamic IP Restrictions with "Deny Action Type" set to "Abort Request", the requests will be aborted and logged as "Request_Cancelled" in the HTTPErr log

By default Dynamic IP Address Restrictions may abort the request if more than 5 concurrent requests come(check what is the configured setting in your server.) And that may be reason why it works for one server and does not work in Azure environment.More details can be found on Security guidelines to detect and prevent DOS attacks targeting IIS/Azure Web Role (PAAS)

Answers 2

What kind of error in browser's console do you see? Have a look on request/response header values IN the browser. Sometimes the configuration is not applied correctly and/or browser expects other headers. Sometimes, Allow-Headers param is too restrictive, try to play with that.

Also, is it reproducible on all browsers?

Answers 3

This is my web config configuration, working for both postman and chrome, you can give it a try:

<system.web>     <compilation debug="true" targetFramework="4.5.2" />     <httpRuntime targetFramework="4.5.2" />     <httpModules>       <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />     </httpModules>   </system.web>   <system.webServer>     <handlers>       <remove name="WebDAV" />       <remove name="ExtensionlessUrlHandler-Integrated-4.0" />       <remove name="OPTIONSVerbHandler" />       <remove name="TRACEVerbHandler" />       <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />     </handlers>     <validation validateIntegratedModeConfiguration="false" />     <modules runAllManagedModulesForAllRequests="true">       <remove name="WebDAVModule" />       <remove name="ApplicationInsightsWebTracking" />       <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />     </modules>     <httpProtocol>       <customHeaders>         <add name="Access-Control-Allow-Origin" value="*" />         <add name="Access-Control-Allow-Headers" value="Content-Type" />         <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />       </customHeaders>     </httpProtocol>   </system.webServer> 

Hope it helps !

Answers 4

You will get this issue due to several reasons. But in this case, I assume that you have install WebDAV and sometimes it make conflict with other modules. So, you better to try to remove that extension first.

enter image description here

Read More

Saturday, July 22, 2017

Web API 404 error Delete request

Leave a Comment

I have a Web API that worked perfectly on development with all kind of HTTP requests (on the same controller), once I moved it to production (shared server, I don't even have access to it) the DELETE requests stopped working (the others are working fine), I get a 404 error:

Requested URL https://www.example.com:443/Rejected-By-UrlScan~/API/Users/DeleteUser/1

Physical Path d:\xx\yy\example.com\Rejected-By-UrlScan

Logon Method Anonymous

Logon User Anonymous

This is (a part of) the web.config:

 <system.web>     <customErrors mode="Off"/>     <authentication mode="None" />     <compilation debug="true" targetFramework="4.5" />     <httpRuntime targetFramework="4.5" />   </system.web>   <system.webServer>     <modules runAllManagedModulesForAllRequests="true">       <remove name="WebDAVModule" />     </modules>     <handlers>       <remove name="WebDAV" />       <remove name="ExtensionlessUrlHandler-Integrated-4.0" />       <remove name="OPTIONSVerbHandler" />       <remove name="TRACEVerbHandler" />       <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />     </handlers>   </system.webServer> 

The Delete Action:

[Authorize] [RoutePrefix("Users")] public class UsersController : ApiController     {     [HttpDelete]     [Route("DeleteUser/{id:int}")]     public void Delete(int id)     {         _UsersRepository.Delete(id);     } 

And the AJAX call:

deleteUser = function (id, callback) {     $.ajax({         url: "../API/Users/DeleteUser/" + id,         type: "DELETE",         success: function () {             callback;         }     }); } 

WebApiConfig.cs:

    public static void Register(HttpConfiguration config)     {         // Web API configuration and services         // Configure Web API to use only bearer token authentication.         config.SuppressDefaultHostAuthentication();         config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));          // Web API routes         config.MapHttpAttributeRoutes();           config.Routes.MapHttpRoute(             name: "DefaultApi",             routeTemplate: "{controller}/{id}",             defaults: new { id = RouteParameter.Optional }         );          //create json formatter and remove all others         var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();         jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();         jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;         config.Formatters.Remove(config.Formatters.FormUrlEncodedFormatter);         config.Formatters.Remove(config.Formatters.XmlFormatter);     } 

An example of a working call on the same Controller:

getUsers = function (callback) {     $.get("../API/Users/GetUsers/", callback); } 

And the Action:

[Route("GetUsers")] public IEnumerable<User> GetUsers() {     return _UsersRepository.GetUsers(); } 

3 Answers

Answers 1

In your IIS do you have the URLScan extension configured ?

https://www.iis.net/downloads/microsoft/urlscan

UrlScan is a security tool that restricts the types of HTTP requests that IIS will process.

The "Rejected-By-UrlScan" in your URL suggests that the extension may be configured to reject "Delete" requests.

You can ask your Administrator of the Server hosting the IIS about whether Delete requests are configured to be allowed in the IIS.

Answers 2

The URL is wrong in the JS snippet. It should be

deleteUser = function (id, callback) {     $.ajax({         url: "[Application_Path]/Users/DeleteUser/" + id,         type: "DELETE",         success: function () {             callback;         }     }); }  [RoutePrefix("Users")] overrides the default routing, so there should be no "API" in the URL. 

You should remove the [Application_Path] and put your virtual directory name or use the @Url.Action

Answers 3

I had to got it to work so I changed the type of the request from DELETE to POST and it works perfectly:

[Authorize] [RoutePrefix("Users")] public class UsersController : ApiController     {     [HttpPost]     [Route("DeleteUser/{id:int}")]     public void Delete(int id)     {         _UsersRepository.Delete(id);     }  deleteUser = function (id, callback) {     $.ajax({         url: "../API/Users/DeleteUser/" + id,         type: "POST",         success: function () {             callback;         }     }); } 
Read More

Saturday, July 1, 2017

Asp.Net WebApi OWIN Authentication

Leave a Comment

After following an online tutorial to use token based authentication using OWIN, I managed to get my test app authenticating against a hard coded username/password, as the demo did.

However, now I want my model from my web application to be used.

My authentication happens, as the demo said, in this bit of code.

namespace UI {     public class AuthorisationServerProvider : OAuthAuthorizationServerProvider     {         public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)         {             context.Validated(); // Means I have validated the client.         }          public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)         {             // Here we validate the user...             var identity = new ClaimsIdentity(context.Options.AuthenticationType);             if (context.UserName == "user" && context.Password == "password")             {                 identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));                 identity.AddClaim(new Claim("username", "user"));                 identity.AddClaim(new Claim(ClaimTypes.Name, "My Full Name"));                 context.Validated(identity);             }             else             {                 context.SetError("Invalid grant", "Username or password are incorrect");                 return;             }         }      } } 

I have a WebAPI controller, which I receive a model from, and ... not sure how to call the above code, from my webapi controller. At the moment, the code above expects a call to myurl/token - that was defined in the startup code.

 public class Startup     {         public void Configuration(IAppBuilder app)         {             // Enables cors origin requests.             app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);              // Config OAuth authorisation server;              var myProvider = new AuthorisationServerProvider();             OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions             {                 AllowInsecureHttp = true, // Live version should use HTTPS...                 TokenEndpointPath = new PathString("/token"),                 AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),                 Provider = myProvider             };              app.UseOAuthAuthorizationServer(options);             app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());              HttpConfiguration config = new HttpConfiguration();             WebApiConfig.Register(config);         }     } 

So, I'm guessing the url from my webapi call should be /token? So, in my (Knockout View model) code on my UI, I tried this:

 Login()     {         var data = {             username : this.login.emailAddress(),             password : this.login.password(),             RememberMe: this.login.rememberMe(),             grant_type: "password"         }          return $.ajax({             type: "POST",             data: data ? JSON.stringify(data) : null,             dataType: "json",             url: "/token",             contentType: "application/json"         }).done((reply) => {             alert("Done!");         });      } 

But, I get an exception:

“error”: “unsupported_grant_type” 

In 'Postman', I am able to authenticate the hard coded username/password.

enter image description here

But I am not sure how to wire up my api call from my UI, to authenticate.

I was hoping to create a 'Login' method on my api controller (ASP.Net WebAPI), like this:

[Route("login"), HttpPost, AllowAnonymous] public ReplyDto Login(LoginRequest login) {     ReplyDto reply = _userService.Login(login.Email, login.Password);     return reply; } 

So, my _userService checks if the user is in the database... if so, call my OAuth authentication here passing a few parameters. But not sure that's possible. Can I call my authentication from this api method? I'd need to remove the /token bit though.

2 Answers

Answers 1

You don't need to create a Login method since you already have it. It's http://localhost:1234/token. This is will generate a token if the user exists and if the password is correct. But get this behaviour you need to implement your own AuthServerProvider by deriving from OAuthAuthorizationServerProvider

public class DOAuthServerProvider : OAuthAuthorizationServerProvider 

and then you would override a method to implement your logic:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)     {          try         {             string allowedOrigin = context.OwinContext.Get<string>(DOAuthStatic.ALLOWED_CORS_ORIGINS_KEY);              if (allowedOrigin != null)             {                 context.OwinContext.Response.Headers[DOAuthStatic.CORS_HEADER] = allowedOrigin;             }              DAuthenticationResponse authResponse = await _authRepository.Authenticate(context.UserName, context.Password);              if (!authResponse.IsAuthenticated)             {                 context.SetError(OAuthError.InvalidGrant, $"{(int)authResponse.AuthenticateResult}:{authResponse.AuthenticateResult}");                  return;             }              if (authResponse.User.ChangePasswordOnLogin)             {                 _userAuthenticationProvider.GeneratePasswordResetToken(authResponse.User);             }              IDictionary<string, string> props = new Dictionary<string, string>             {                 {                     DOAuthStatic.CLIENT_NAME_KEY, context.ClientId ?? string.Empty                 }             };              ValidateContext(context, authResponse, props);         }         catch (Exception ex)         {             DLogOAuth.LogException(ex, "DCO0407E", "OAuthServerProvider - Error validating user");              throw;         }     } 

You are almost there, you just need to do two more steps:

  1. Add the AuthorizeAttribute on your method or controller to restrict access for unauthenticated users.
  2. Add the access token you request header. If you skip this step you should get a 401 HTTP status code, meaning unauthorized. This is how you can confirm that the authorise attribute that you added in step one works.

Here is a great series of tutorials that explains everything really well: Token based authentication (way better than I have :) )

Answers 2

Change the Content Type "application/json" to "application/www-form-urlencoded"

You are Sended Data in Postman "application/www-form-urlencoded" format. But in Your Code Using "application/Json" the Content Type Mismatch. So,the Data is Not Send Proper Format.

You Can Change If it's Working Fine.

Read More

Sunday, June 11, 2017

UrlHelper.Link returns undesired parameters

Leave a Comment

If I call UrlHelper.Link within an API call which has a parameter matching an optional parameter of the API endpoint I'm attempting to obtain an URL for, UrlHelper.Link returns a URL with values from the current request no matter how I try to exclude the optional parameter from the link.

e.g.

[HttpGet] [Route("api/Test/Stuff/{id}")] public async Task<IHttpActionResult> GetStuff(int id) // id = 78 {     string link = Url.Link("Mary", new     {         first = "Hello",         second = "World"     });      string link2 = Url.Link("Mary", new     {         first = "Hello",         second = "World",         id = (int?)null     });      string link3 = Url.Link("Mary", new     {         first = "Hello",         second = "World",         id = ""     });      return Ok(new     {         link,         link2,         link3     }); }  [HttpGet] [Route("api/Test/Another/{first}", Name = "Mary")] public async Task<IHttpActionResult> AnotherMethod( [FromUri]string first, [FromUri]string second = null, [FromUri]int? id = null) {     // Stuff     return Ok(); } 

GET http://localhost:53172/api/Test/Stuff/8

returns

{   "link": "http://localhost:53172/api/Test/Another/Hello?second=World",   "link2": "http://localhost:53172/api/Test/Another/Hello?second=World&id=8",   "link3": "http://localhost:53172/api/Test/Another/Hello?second=World&id=8" } 

How do you get Url.Link to actually use the values you pass it rather than pull it from the current api request when they are not presented or assigned to null or empty string?

I believe the issue is very similar to ....

UrlHelper.Action includes undesired additional parameters

But this is Web API not MVC, not an action and the answers provided do not seem to yield an obvious solution to this issue.

EDIT: I've updated the code as the original code didn't actually replicate the issue. I've also included a request URL and the response returned, which I've tested. Whilst this code demonstrates the issue, the code I'm trying to find a fix for is not passing an anonymous type to UrlHelper, instead its a class which generates a timestamp and hash and has 4 optional parameters. If there's another solution which doesn't require omitting the optional parameters in the structure passed to UrlHelper I'd like to have it, as it'll save me from making a lot of changes to the code.

1 Answers

Answers 1

Do not include the id when passing the route values. In fact it should not allow you to compile as

Cannot assign <null> to anonymous type property

public async Task<IHttpActionResult> GetStuff(int id) // id = 78 {     string myUrl = Url.Link(         "Mary",          new          {              first = "Hello World"         });      //...other code } 

Tested with web api 2 and id was not included when linking to other action.

[RoutePrefix("api/urlhelper")] public class UrlHeplerController : ApiController {      [HttpGet]     [Route("")]     public IHttpActionResult GetStuff(int id) {         string myUrl = Url.Link(             "Mary",             new {                 first = "Hello World",            });         return Ok(myUrl);     }      [HttpGet]     [Route(Name = "Mary")]     public IHttpActionResult AnotherMethod(     [FromUri]string first,     [FromUri]string second = null,     [FromUri]int? id = null) {         // Stuff         return Ok();     } } 

Calling

client.GetAsync("/api/urlhelper?id=78") 

routed to the GetStuff action and the link generated

"http://localhost/api/urlhelper?first=Hello%20World" 

Even when tested with

string myUrl = Url.Link(     "Mary",     new {         first = "Hello World",         id = ""     }); 

id was not included in the generated link.

Read More