P
P
Peter2021-12-15 21:08:31
.NET
Peter, 2021-12-15 21:08:31

How to implement the "return" of the desired version of the site?

Good afternoon.
I have a small test site, mobile layout and desktop layout, but how to implement all this in net core?
So that the web api, for example, seeing the user agent of a mobile device, would give the layout for the mobile phone, and if the desktop gave the site assembly for the desktop.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2021-12-15
@NeiroNx

It is a question of IIS as I understood.
Create an address rewriting rule in the conditions add {HTTP_user-agent} according to the pattern .*Mobile.* (all mobile agents must contain the word Mobile )

<rule name="test" enabled="false">
 <match url="(.*)" />  
  <conditions>
   <add input="{HTTP_user-agent}" pattern=".*Mobile.*" />
  </conditions>
  <action type="Redirect" url="/mobile.html" />
</rule>

R
Roman, 2021-12-16
@yarosroman

Well, the logic for both versions will still be the same
1. Do everything based on CSS, the same bootstrap allows you to make a mobile version at the same time.
2. Since the business logic remains, we do this trick
https://docs.microsoft.com/ru-ru/dotnet/api/micros...

public class ViewLocationExpander: IViewLocationExpander {

    /// <summary>
    /// Used to specify the locations that the view engine should search to 
    /// locate views.
    /// </summary>
    /// <param name="context"></param>
    /// <param name="viewLocations"></param>
    /// <returns></returns>
    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) {
        //{2} is area, {1} is controller,{0} is the action
        string[] locations = new string[] { "/Views/{2}/{1}/{0}.cshtml"};
        return locations.Union(viewLocations);          //Add mvc default locations after ours
    }


    public void PopulateValues(ViewLocationExpanderContext context) {
        context.Values["customviewlocation"] = nameof(ViewLocationExpander);
    }
}

services.Configure<RazorViewEngineOptions>(options => {
        options.ViewLocationExpanders.Add(new ViewLocationExpander());
    });

UPD: All the same, the results are cached, while working, well, option 2, writing your own RazorViewEngine
https://github.com/dotnet/aspnetcore/blob/main/src
... us to the mobile zone. but 2 times to write all controllers, plus you can make different versions.

V
Vlad, 2022-01-03
@KislyFan

Use Roman 's solution or define your own middle-ware, where the browser type will be determined.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question