Getting the HttpRequest Extension Method written for MVC for working in Web Api

I am working with OAuth 2.0 for MVC, the .NET library for Oauth2. However, I am creating a Web Api project, and I hope this library will work with Web Api.

The problem I am facing is that the library uses two extension methods on the HttpRequestBase, which it calls from the controller.

Here are the extension methods:

public static string GetToken(this HttpRequest request) { var wrapper = new HttpRequestWrapper(request); return GetToken(wrapper); } public static string GetToken(this HttpRequestBase request) { if (request == null) return String.Empty; // Find Header var headerText = request.Headers[OAuthConstants.AuthorzationHeader]; if (!String.IsNullOrEmpty(headerText)) { var header = new AuthorizationHeader(headerText); if (string.Equals(header.Scheme, "OAuth", StringComparison.OrdinalIgnoreCase)) return header.ParameterText.Trim(); } // Find Clean Param var token = request.Params[OAuthConstants.AuthorzationParam]; return !String.IsNullOrEmpty(token) ? token.Trim() : String.Empty; } 

In an MVC project, they simply call Request.GetToken () from the controller. Of course, a Web Api request is an HttpRequestMessage. I am afraid that the difference between HttpRequest and the HttpRequest post is beyond my scope right now.

Is it possible to convert this extension method to work with HttpRequestMessage or somehow make it work in Web Api ??

Thanks!

+1
source share
1 answer

All the properties you used are still available (assuming OAuthConstants.AuthorzationParam is set in the query string?)

 using System; using System.Linq; using System.Net.Http; namespace YourApp { public static class Extensions { public static string GetToken(this HttpRequestMessage request) { if (request == null) return String.Empty; // Find Header var headerText = request.Headers.GetValues(OAuthConstants.AuthorzationHeader).SingleOrDefault(); if (!String.IsNullOrEmpty(headerText)) { //Brevity... } // Find Clean Param var token = request.GetQueryNameValuePairs().SingleOrDefault(x => x.Key == OAuthConstants.AuthorzationParam).Value; return !String.IsNullOrEmpty(token) ? token.Trim() : String.Empty; } } 

}

controller

 using System.Collections.Generic; using System.Web.Http; using YourApp; namespace YourApp.Controllers { public class FoosController : ApiController { public IEnumerable<string> Get() { var token = Request.GetToken(); return null; } } } 
+1
source

Source: https://habr.com/ru/post/1440435/


All Articles