Asp.Net Web Api And Andriod Interface docking development experience , Share it with your friends !

 

I've been in a hurry to get Asp.Net Web Api And Andriod Interface development docking work !

I just heard that I'm going to use Asp.Net Web Api Go with Andriod That end does interface docking work , It's my first contact Web Api, I started learning and developing , I didn't even have time to understand and digest some knowledge , I have to do the project , I feel like I'm still in a hurry , Very busy , A lot of things are learned on the subway , Thank you very much ( Artech  and   Zhang Shanyou  ) Great God's blog Help and inspiration .

The project directory is as follows :

Because of what I do here web api It provides a complete set of project interfaces , quite a lot api Interfaces require login authorization , Some of them are anonymous .

==》  about External development Of web api Interface , It's all possible   “ Anonymous access ”  perhaps yes  "CORS Authorization mechanism ", Or to limit it web api Frequency of calls .

【CORS Authorization mechanism - knowledge 】:http://www.cnblogs.com/artech/tag/ASP.NET Web API

【 Limit Web Api Access frequency 】:http://www.cnblogs.com/shanyou/p/3194802.html

For what web api need Anonymous development , What needs login authorization to access , You can make a general one Attribute To do it .

Like the following code , For reference only :

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAV4AAAArCAIAAAC/0XeLAAAFB0lEQVR4nO2dPU/bQBjH+zkYPCBRiXhkYK3oclKHrvABKrHhj4CqKhJBoqpOiI5UFDFVmSIBA6pqqSNL46Ht1DDBEtrh5g4m53t5zvbFAZzj/5OFyPnlXuz7+fEFH8/G43/j8T8BAAAKz6AGAIDNU1FDt9td03nsEgHQap6EGrrd7tu3727Hf+UCNQBQTphqMAIE6YX8o4caMs4ixjMhxCCJksH9lhqAFjEHahgOh7675P2/ZHGoIeMsKmA8gxrAU6XtakjTtNPp+O7VRA0OAUg1lGwDQDi0Wg1pmi4tLUVR5Lsj1ABAQ9qrBukFLzWsVeGnhiIhV8MgUR837tL1hLt9BomSBMDc0VI1qF7wUsPW1la5Gs7PzmuONTCeWWoQuj4GSdH7ZXp+EAQWYL5poxoML3ip4eTkpFwNe3vvG0QN+jZKDKEEDnjiACHQOjUMh8NOp2N0Oa/dy9Wwvr4+SzUQjwxQAwiB1qmhORsbG+V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5S6eq4L0viXDkHru1bUuYjLzPwLo7ZlxFiWJOQpZo/WohlKHQsx2sM5pEISjBgDADIEaAAAEUAMAgABqAAAQQA0AAAKoAQBAADUAAAigBgAAQThqmMspngBoK+GoYV4ngJs55AuUAHjyH6sXepPAYsCFAAAAAElFTkSuQmCC" alt="" />

 1 /// <summary>
2 /// Basic verification Attribtue, In order to use WebApi Request permission processing
3 /// </summary>
4 public class BasicAuthenticationAttribute : ActionFilterAttribute
5 {
6 private static Uni2uni.Framework.Cache.ICache cache = CacheFactory.Redis(RedisDb.User);
7
8 /// <summary>
9 /// Check whether the user has the information WebApi Permission to request execution
10 /// </summary>
11 /// <param name="actionContext"></param>
12 public override void OnActionExecuting(HttpActionContext actionContext)
13 {
14 if (actionContext.Request.Headers.Contains("Set-Cookie"))
15 {
16 var accessToken = actionContext.Request.Headers.GetValues("Set-Cookie");
17 Dictionary<string, string> item = new Dictionary<string, string>();
18 accessToken.FirstOrDefault().ToString().Split('&').Each(i =>
19 {
20 var itemLine = i.Split('=');
21 item.Add(itemLine[0], itemLine[1]);
22 });
23 // Decrypt users token value , See if you're logged in
24 string tokenValue = System.Web.HttpUtility.UrlDecode(item["access_token"]);
25 if (ValidateToken(tokenValue))
26 {
27 base.OnActionExecuting(actionContext);
28 }
29 else
30 {
31 actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
32 actionContext.Response.Content = new StringContent("The request has no token or toke id expired,is invalid !",
33 Encoding.UTF8, "text/plain");
34 }
35 }
36 else
37 {
38 // Check web.config Whether permission verification is required for configuration
39 bool isRquired = (WebConfigurationManager.AppSettings["WebApiAuthenticatedFlag"].ToString() == "true");
40 if (isRquired)
41 {
42 // If you ask for Header It doesn't contain token, Then determine whether it is an anonymous call
43 var attr = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
44 bool isAnonymous = attr.Any(a => a is AllowAnonymousAttribute);
45
46 // It's an anonymous user , Then continue ; Non anonymous users , Throw out “ Unauthorized access ” Information
47 if (isAnonymous)
48 {
49 base.OnActionExecuting(actionContext);
50 }
51 else
52 {
53 actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
54 actionContext.Response.Content = new StringContent("The request is Unauthorized,is nto allow!",
55 Encoding.UTF8, "text/plain");
56 }
57 }
58 else
59 {
60 base.OnActionExecuting(actionContext);
61 }
62 }
63 }
64
65 /// <summary>
66 /// Verify login authorization
67 /// </summary>
68 /// <param name="token"></param>
69 /// <returns></returns>
70 public bool ValidateToken(string token)
71 {
72 if (!string.IsNullOrEmpty(token))
73 {
74 var model = cache.Get<LoginMember>(token);
75 Logger.Error("2: In the request ...:model:" + model == null ? " non-existent " : model.UserName);
76 return model != null ? true : false;
77 }
78 return false;
79 }
80 }

==》【 OData 】

Considering the limitation of mobile project , Aimed at ( Query page , Query filtering , Sort ) aspect , I used it Asp.Net Web Api OData, Because our project architecture only supports .Net 4.0, The latest one has arrived  Asp.Net Web Api 2 OData 了 .

OData Related knowledge links :

http://www.cnblogs.com/Kummy/p/3486097.html

http://www.cnblogs.com/shanyou/archive/2013/06/11/3131583.html

==》【 Web Api Post [FromBody] Support simple data types .】 

stay Web Api In development , We'll find a problem , Post Simple data types are no longer supported .

As the following example :

[AllowAnonymous]
[HttpPost]
public string Test([FromBody]string Name)
{
return null;
}

We will find that , This Post What are the types that come here null

So I looked for it for a long time , A solution to the problem was found .

Address : http://weblog.west-wind.com/posts/2012/Sep/11/Passing-multiple-simple-POST-Values-to-ASPNET-Web-API

==》【 Web Api , ordinary ( Universal upload as well as General paging )】

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAARgAAAAcCAIAAAA1Cjd5AAADK0lEQVR4nO2bu27bMBSG8xweNGQIYGj04LVAFwId+hQBMvIRskaZCiJIRxeNx0CTgHQLIqCjl4IPUGWyF7cL5w60KN50sU2HbfV/EAJbl0MaOJ/OoRyfCQDA0ZzFngAA/wMQCYAAQCQAAgCRAAgARAIgABAJgADEEaksyyjjAnAi4og0nU7/DZc4IwlhPOIMCprQwngB/kbiiJQkSZqmR7p0+3Qzz2Zyu3++E0LMs5n62wlnJBmUlrZIBU1q3iirDxRJm2gS+VYwDqKJlOd5r0vLVXXxUE0W1cVDtVxV+iFp0cfPH+6f726fbvLVo5JKbl3Dc0YIIfuqUFBDn4Lun5+cHTLqgSKp6RX0zbQfL9FEEkL0ujRZVNcvr99+/Lx+eZ0sDJHm2ez9p3eb7cbaKQZUJM4IYXzPVilINsYR6YBRwb7EFEkIkWVZmqbr9XrfCPNsdrW8tPYMq0jSIzPXdsnWNES7xFM5aJxsobdRKmELmhDGqNZbaacRxvURd5Hb4rgiNWfWk7KjafM1PeKMOGP49rlD+D+yPOqLMC5iilSWZZqmeZ63nTZZVPqmHzq8IjUpZt+1myRQ5adfpILqqdbULa0RbBZaek6bI3bFcV+4xcaK1rZG4ow6DZ+nYHXXM3Oq/gijI5pIvRaJWqRf29+uSFfLS32N9PX7l4FDW4sH/21bve0Vyd7vvaCugY5IRuK3xjFFMhRRmti5bMQz21KnesiI2vD+Idqm6oswPmI+teu2SHSKtNlupEtyGyySkyNa1egSqc0kjwDy/fEiqTiOSJ6JdIqk3nFGVL7bV0i/3Ka39yP7IoyPOCKdn5/3WiQ6W7sDsR8ZGP2N2XXZbY+ehPJStfIx7v3+vrFPpK44bmund4TeG0FLRbJKcP0ZmT0l3xBNg6ofLRjjvgijI45IQyw6Be6jt3oPZySh1H7W4Mt2d1Hd/rDBFqluq5qHDfZcfHEskbxLe49ITtU1riSUqiucZyy+IfSv1Jqj7RFGBv7XTjLeWykIAkSSQCRwFBBJApHAUUAkAAIAkQAIAEQCIAAQCYAAQCQAAoCfmgMQAPzUHJyOEf1O/g9pw70Igde0kgAAAABJRU5ErkJggg==" alt="" />

Code for reference only , as follows :

   [BasicAuthentication]
public abstract class ApiControllerBase : ApiController
{
#region Common Pager
/// <summary>
/// Extend a page to the result set
/// </summary>
/// <typeparam name="T"> Entity </typeparam>
/// <param name="_defaultSetting"> Page setup </param>
/// <param name="options"> Filter criteria collection </param>
/// <param name="_list"> Collection to be paged </param>
/// <returns></returns>
public PageResult<TEntity> GetPager<TEntity>(ODataQueryOptions<TEntity> options, IEnumerable<TEntity> _list, int PageSizeCount = 6) where TEntity : class
{
ODataQuerySettings settings = new ODataQuerySettings
{
PageSize = PageSizeCount
};
IQueryable results = options.ApplyTo(_list.AsQueryable(), settings);
Request.GetInlineCount();
return new PageResult<TEntity>(
results as IEnumerable<TEntity>,
Request.GetNextPageLink(),
Request.GetInlineCount());
}
#endregion #region Common Upload
/// <summary>
/// General upload picture - operation
/// </summary>
/// <typeparam name="T"> Upload entity </typeparam>
/// <param name="dirPath"> Upload road strength </param>
/// <param name="fileNameAction"> File name custom extension </param>
/// <param name="Entity"> Entity name </param>
/// <returns> Is the picture uploaded successfully </returns>
[NonAction]
public Hashtable CommonUpload<T>(string dirPath, Action<string> fileNameAction, out T Entity) where T : class
{
var queryp = Request.GetQueryNameValuePairs(); // Gets the key value collection of the query string
Entity = GetUploadEntity<T>(queryp); // Entity assignment operation // Check if it is multipart/form-data
if (!Request.Content.IsMimeMultipartContent("form-data"))
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
// File save directory path
string SaveTempPath = dirPath;
String dirTempPath = HttpContext.Current.Server.MapPath(SaveTempPath);
Logger.Error(" File path :" + dirTempPath);
// Set upload directory
var provider = new MultipartFormDataStreamProvider(dirTempPath); //Logger.Error("queryp Parameters :" + param);
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<Hashtable>(o =>
{
Hashtable hash = new Hashtable();
hash["error"] = 1;
hash["errmsg"] = " Upload error ";
var file = provider.FileData[0];//provider.FormData
string orfilename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');
FileInfo fileinfo = new FileInfo(file.LocalFileName); Logger.Error(" Maximum file size :" + fileinfo.Length);
Logger.Error(" Maximum format :" + orfilename);
// Maximum file size
int maxSize = 10000000;
if (fileinfo.Length <= 0)
{
hash["error"] = 1;
hash["errmsg"] = " Please select upload file .";
}
else if (fileinfo.Length > maxSize)
{
hash["error"] = 1;
hash["errmsg"] = " Upload file size exceeds limit .";
}
else
{
string fileExt = orfilename.Substring(orfilename.LastIndexOf('.'));
// Define the file extensions allowed to upload
String fileTypes = "gif,jpg,jpeg,png,bmp";
if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
{
hash["error"] = 1;
hash["errmsg"] = " Upload file extension is not allowed .";
}
else
{
//String ymd = DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo);
//String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo);
//String finalFileName = newFileName + fileExt;
string excute_FileName = string.Empty;
fileNameAction = (i) => { excute_FileName = i; };
fileinfo.CopyTo(Path.Combine(dirTempPath, excute_FileName), true);
fileinfo.Delete();
hash["error"] = 0;
hash["errmsg"] = " Upload successful ";
hash["filePathUrl"] = excute_FileName;
}
}
return hash;
});
return null;
} /// <summary>
/// Reflection dynamic entity assignment - operation
/// </summary>
/// <typeparam name="Entity"></typeparam>
/// <param name="queryp"></param>
/// <returns></returns>
[NonAction]
public Entity GetUploadEntity<Entity>(IEnumerable<KeyValuePair<string, string>> queryp) where Entity : class
{
var entity = typeof(Entity);
Object model = entity.Assembly.CreateInstance(entity.FullName, true);
var props = entity.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (PropertyInfo propertyInfo in typeof(Entity).GetProperties())
{
queryp.Each(i =>
{
if (i.Key.Equals(propertyInfo.Name.ToString()))
{
propertyInfo.SetValue(model, i.Value, null);
}
});
}
return (Entity)model;
}
#endregion
}

hope , I would like to give you advice .

I wish you all the best , Happy New Year's day !

Precipitate oneself in the lonely days , Find yourself in the days of the program , I stick to my dream !
 

Asp.Net Web Api And Andriod Interface docking development of more related articles

  1. Asp.Net Web Api And Andriod Interface docking development experience , Share it with your friends !

    I've been in a hurry to get Asp.Net Web Api And Andriod Interface development docking work ! I just heard that I'm going to use Asp.Net Web Api Go with Andriod That end does interface docking work , It's the first time I've been in touch with Web ...

  2. Web Api And Andriod Interface docking development experience

    I've been in a hurry to get Asp.Net Web Api And Andriod Interface development docking work ! I just heard that I'm going to use Asp.Net Web Api Go with Andriod That end does interface docking work , It's the first time I've been in touch with Web ...

  3. ASP.NET Web API Realize the development of wechat public platform ( One ) Server authentication

    Recently, WeChat's official account is ready to do some activities. , It can't be done by the fixed wechat public platform template , So I was asked to develop wechat background for you . In view of this, I also tried to develop wechat background for the first time , So I stepped on a lot of pits , This series of blog will describe the implementation of WeChat official account's functions. . precondition ...

  4. ASP.NET Web API Realize the development of wechat public platform ( 3、 ... and ) Custom menu

    Previous process , After the completion of server binding and acquisition access_token after , This article mainly describes how to realize wechat custom menu . Official example effect Before the start . Custom menus include at most 3 A first-class menu , Each primary menu can contain at most 5 Two level menus . ...

  5. ASP.NET Web API Realize the development of wechat public platform ( Two )access_token And timing tasks

    Take on the last one , Today, we mainly talk about how to get wechat regularly access_token Function realization . access_token First of all, we follow the development guide of wechat , Any operation on wechat should use legal access access_token, WeChat ...

  6. Travel map beta edition asp.net web api unit testing

    Travel map beta edition asp.net web api unit testing Test interface :http://120.27.7.115:1010/Help Test purpose Test each interface unit , Ensure the reliability of each interface . Unit description notes ...

  7. 【 turn 】WCF and ASP.NET Web API Choice in application

    The article citations :http://www.cnblogs.com/shanyou/archive/2012/09/26/2704814.html Recently released Visual Studio 2012 And .NET 4. ...

  8. ASP.NET Web API—— choice Web API still WCF

    WCF yes .NET One stop framework for platform service development , Then why do we have ASP.NET Web API Well ? Simply speaking ,ASP.NET Web API There is only one thing to consider in the design and construction of , That's it HTTP, and WCF The main purpose of the design is to test ...

  9. WCF and ASP.NET Web API Choice in application

    Share : I have some alicloud coupons , You can get a maximum discount of 50% for purchasing or upgrading the corresponding products of Alibaba cloud with coupons ! Receipt address :https://promotion.aliyun.com/ntms/act/ambassador/shareto ...

Random recommendation

  1. For front-end ,「 Wechat applet 」 It's not beautiful

    Wechat app open public beta ,9 At the end of the month I wrote an article 「 Wechat applet 」 coming , The last sentence :" Thank goodness , I'm still a front end ". This hot new thing is always exciting , Thanks for The Times . however , When I'm really a developer ...

  2. Zabbix monitor nginx-rtmp status(html edition )

    nginx-rtmp Turn on stats # nginx(--add-module=nginx-rtmp-module-master) nginx.conf: server { listen ; locat ...

  3. jquery Paging plug-ins

    css Code : /* Pagination */ .pageList { clear: both; overflow: hidden; } .pageList a, .pageList span { border: 1px ...

  4. Codeforces 1C Ancient Berland Circus

    Portal The question The coordinates of three vertices of a regular polygon are given , Find the minimum area of this regular polygon . analysis For narrative purposes , Defines the unit center angle of a regular polygon u Is the center angle of an edge of a regular polygon to its circumscribed circle ( That is, the center angle of a string of circumscribed circle ). (1) polygon ...

  5. PTVS stay Visual Studio Installation in

    Download link , Click here PTVS yes VS Under the python Developing a plug-in 1. When the download is complete , Double-click on the run , Installation completed 2. Explain script : open VS, file found - newly build - project , On the left side of the new project page, the tree menu is installed -> Templates -> ...

  6. React16.x Feature editing

    This paper has sorted out React 16.x The new concepts and concepts api And application scenarios . more React You can subscribe to the series blog 16.0 Fiber stay 16 Previous versions of the rendering process can be thought of as a one-time dive ...

  7. 【1】【leetcode-115】 Different subsequences distinct-subsequences

    Different subsequences distinct-subsequences(hard) ( Forget , A typical ) Given a string  S  And a string  T, Calculated at  S  In the subsequence of  T  Number of occurrences . A subsequence of a string refers to , By deleting ...

  8. Golang Single quotation mark of 、 Double quotes and back quotes

    Go String type of language string In essence, it is different from string types of other languages : Java Of String.C++ Of std::string as well as Python3 Of str Types are just fixed width character sequences Go The language string is a string using ...

  9. Torch or Numpy

    1. What is? NumpyNumpy System is Python An open source numerical computing extension , use python Implementation of scientific computing package . This tool can be used to store and process large matrices , Including powerful N Dimensional array object Array, More mature function library, etc .num ...

  10. MySQL Master slave replication bootstrap in production environment

    MySQL In addition to the replication parameters we encountered when building the master and slave , There are two more : 1.log-slave-updates This parameter is used to configure whether the binary log function is started on the slave library , Not on by default , If it is turned on, then from the library ...