Reputation: 151
I have an old Controller class in my company which inherits ApiController
.
One of the actions are a POST
endpoint that receives data from browser.
Since I'm in the ApiController
, I don't have the built-in property IsMobile
to detect.
So, How do I Detect if Request is from Mobile in ApiController
?
Any alternatives to suggests ?
Upvotes: 1
Views: 3263
Reputation: 151
As suggested by the initial answers, the key is using UserAgent
.
I found this answer which I wrapped up in an ActionFilter
in case I would like to use it thou out multiple actions
/// <summary>
/// This action filter sets Request's properties with a "BrowserCapabilitiesFactory" object. <br/>
/// To get it, use <b>Request.Properties.TryGetValue("UserBrowser", out yourObjectToSet);</b>. <br/>
/// With that, you can check browser details of the request. Use this for <b>ApiController</b> actions. <br/>
/// If browser was not found or any exception occured in filter, then the value of the key will be set to null,
/// By doing that , ensures that the Properties will always have a key-value of UserBrowser
/// </summary>
public class GetUserBrowserActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
try
{
// ============================== Get User agent and parse it to a strongly type object ============================== //
var userAgent = HttpContext.Current.Request.UserAgent;
var userBrowser = new HttpBrowserCapabilities { Capabilities = new Hashtable { { string.Empty, userAgent } } };
var factory = new BrowserCapabilitiesFactory();
factory.ConfigureBrowserCapabilities(new NameValueCollection(), userBrowser);
actionContext.Request.Properties.Add("UserBrowser", userBrowser);
}
catch (Exception ex)
{
actionContext.Request.Properties.Add("UserBrowser", null);
}
}
}
Upvotes: 0
Reputation: 39085
You might look at the User-Agent header, and look for hints of mobile client:
var userAgent = Request.Headers.UserAgent.ToString();
You might be able to look for certain strings like 'mobile' or 'mobi' (or search for multiple alternative keywords).
Here's a page that lists mobile client user agents: https://developers.whatismybrowser.com/useragents/explore/hardware_type_specific/mobile/7
Update:
Here's a library that's already doing something similar with the user-agent header: https://github.com/wangkanai/Detection
Upvotes: 2